/*
 * File: browserCache.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package servlets;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import foxtrotbravo.Config;

/**
 * The Class browserCache.
 * 
 * @author Dude
 */
public class BrowserCache
{

  /**
   * Handle cache.
   * 
   * @param req
   *          the req
   * @param resp
   *          the resp
   * @param cache_expire
   *          the cache_expire
   * @param fileName
   *          the file name
   * @return true, if successful
   */
  public static boolean handleCache(HttpServletRequest req,
      HttpServletResponse resp, long cache_expire, String fileName)
  {
    if (!Config.isDev())
    {
      resp.setHeader("Pragma", "public");
      resp.setHeader("Cache-Control", "public, max-age=" + cache_expire);
      resp.setDateHeader("Expires", System.currentTimeMillis() + cache_expire
          * 1000);
      File f = new File(fileName);
      long lastmod = f.lastModified();
      long ims = req.getDateHeader("If-Modified-Since");
      // Drop 30 seconds so to compensate for weird fluctuations.
      if (ims != -1 && ims > lastmod - 30000)
      {
        resp.setDateHeader("Last-Modified", ims);
        resp.setStatus(304);
        return true;
      }
      resp.setDateHeader("Last-Modified", lastmod);
    }
    return false;
  }
}
